package com.moli.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moli.constans.SystemConstants;
import com.moli.domain.entity.LoginUser;
import com.moli.domain.entity.User;
import com.moli.mapper.MenuMapper;
import com.moli.mapper.UserMapper;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Author： XC
 * @Date： 2023-06-04 09:31
 * @Description： 用户详细信息服务实现类
 */


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private MenuMapper menuMapper;


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1.根据用户名查询用户信息 用LambdaQueryWrapper封装查询条件
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		//构造查询条件，使用方法引用
		queryWrapper.eq(User::getUserName,username);
		User user = userMapper.selectOne(queryWrapper);
		//2.判断是否查到用户  如果没查到抛出异常
		if(Objects.isNull(user)){
			throw new RuntimeException("用户不存在");
		}
		//3.返回用户信息
		//根据用户查询权限信息 添加到LoginUser中
		//如果是管理员身份 type=1时 返回对应的菜单
		if(user.getType().equals(SystemConstants.ADMAIN)){
			List<String> list = menuMapper.selectPermsByUserId(user.getId());
			return new LoginUser(user,list);
		}
		//封装成UserDetails对象返回
		return new LoginUser(user,null);
	}
}